package com.nageoffer.jobtrain.projects.service.handler.remind.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.nageoffer.jobtrain.projects.common.biz.user.UserContext;
import com.nageoffer.jobtrain.projects.dao.entity.ContestDO;
import com.nageoffer.jobtrain.projects.dao.entity.MessageDO;
import com.nageoffer.jobtrain.projects.dao.mapper.ContestMapper;
import com.nageoffer.jobtrain.projects.dao.mapper.MessageMapper;
import com.nageoffer.jobtrain.projects.handler.ContestNotifyWebSocketHandler;
import com.nageoffer.jobtrain.projects.service.handler.remind.ContestRemindTemplate;
import com.nageoffer.jobtrain.projects.service.handler.remind.dto.ContestRemindDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 站内APP通知实现类
 * author：唐晨
 */
@Component
@RequiredArgsConstructor
public class SendAppMessageRemindContestTemplate implements ContestRemindTemplate {
    private final MessageMapper messageMapper;
    private final ContestMapper contestMapper;
    private final ContestNotifyWebSocketHandler contestNotifyWebSocketHandler;

    // 实现站内APP通知功能
    @Override
    public boolean remind(ContestRemindDTO requestParam) {
        LambdaQueryWrapper<ContestDO> queryWrapper = Wrappers.lambdaQuery(ContestDO.class)
                .select(ContestDO::getTitle)
                .eq(ContestDO::getId, requestParam.getContestId())
                .eq(ContestDO::getStatus, 1)
                .eq(ContestDO::getDelFlag, 0);
        ContestDO contestDO = contestMapper.selectOne(queryWrapper);
        // 构建 WebSocket 消息
        String contestNotifyMessage = "您报名的" + contestDO.getTitle() + "竞赛将在" + requestParam.getRemindTime() +
                "分钟后正式开始！";
        MessageDO messageDO = MessageDO.builder()
                .receive(UserContext.getUsername())
                .title("竞赛即将开始通知：")
                .content(contestNotifyMessage)
                .receive(requestParam.getPhoneNumber())
                .build();
        messageMapper.insert(messageDO);
        // 实现将消息通过websocket协议主动推送到前端展示
        contestNotifyWebSocketHandler.sendMessage(requestParam.getPhoneNumber(), contestNotifyMessage);
        return true;
    }
}
